//
//  JKImageDiskCache.m
//  JackToolsBox
//
//  Created by Jack Xue on 2019/12/4.
//  Copyright © 2019 Jack Xue. All rights reserved.
//

#import "JKImageDiskCache.h"
#import "JKWebImage.h"          //用于自定义缓存存放位置

#define jk_target_string [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:jk_disk_file]

static BOOL _localUpdate;       //有新数据写入，需要更新diskArray
static NSArray *_diskRefArray;  //硬盘缓存索引

@implementation JKImageDiskCache
+(void)addImageToDisk:(UIImage*)image withKey:(NSString*)key{
    //先检查是否有缓存文件夹
    NSFileManager *manager = [NSFileManager defaultManager];
    BOOL isDir = YES;
    if (![manager fileExistsAtPath:jk_target_string isDirectory:&isDir]) {
        //需要创建缓存文件夹
        [manager createDirectoryAtPath:jk_target_string withIntermediateDirectories:YES attributes:nil error:nil];
    }//@end - 检查缓存文件夹
    
    //将缓存图片存入
    NSString *imagePath = [NSString stringWithFormat:@"%@/%@.png",jk_target_string,key];
    [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
    _localUpdate = YES;
}

+(void)removeImageFromDisk{
    NSFileManager *manager = [NSFileManager defaultManager];
    BOOL isDir = YES;
    if (![manager fileExistsAtPath:jk_target_string isDirectory:&isDir]) {
        //没有缓存文件夹-->不需要做任何清除缓存的操作
        return;
    }
    NSError * err = nil;
    [manager removeItemAtPath:jk_target_string error:&err];
    if (err) {
        NSLog(@"清除硬盘缓存失败");
    }else{
        _localUpdate = YES;
        NSLog(@"成功清除硬盘缓存");
    }
}

+(UIImage*)searchImageInDiskWithKey:(NSString*)key{
    NSFileManager *manager = [NSFileManager defaultManager];
    //1.先取出reference数组
    if (!_diskRefArray || _localUpdate) {
        _diskRefArray = [manager contentsOfDirectoryAtPath:jk_target_string error:nil];
        _localUpdate = NO;
//        NSLog(@"获取本地结果%@",_diskRefArray);
    }
    
    //2.查询硬盘中是否命中
    if ([_diskRefArray containsObject:[NSString stringWithFormat:@"%@.png",key]]) {
        NSString *imagePath = [NSString stringWithFormat:@"%@/%@.png",jk_target_string,key];
        UIImage *result = [UIImage imageWithData:[manager contentsAtPath:imagePath]];
        return result;
    }else{
        return nil;
    }
}



@end
